import dayjs from "dayjs";
import { message } from "@/utils/message";
import { tags_list } from "@/api/tag"
import { user_list } from "@/api/user"
import { customer_list } from "@/api/customer"
import { type Ref, reactive, ref, onMounted, toRaw, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";

import { useUserStoreHook } from "@/store/modules/user";

export function useRole(detailRef: Ref) {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_cd_fq_table: false, // 废弃客池列表
  })

  const shortcuts = [
    {
      text: "上周",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      }
    },
    {
      text: "上个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      }
    },
    {
      text: "三个月前",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      }
    }
  ];
  const labelList = ref([])
  const sourceList = ref([{
    value: "exchange",
    label: "兑领"
  }, {
    value: "third",
    label: "第三方自导入"
  }])
  const userList = ref([])
  const form = reactive({
    type: "feiqi",
    keyword: "",
    tag_id: "",
    source_by: "",
    address: "",
    entry_at: "",
    update_at: "",
    target_staff_id: "",
    called_times: "",
    page: 1,
    size: 10
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "企业名称",
      prop: "company_name",
      minWidth: 200
    },
    {
      label: "客户名称",
      prop: "name",
      minWidth: 100
    },
    {
      label: "联系电话",
      prop: "phone",
      minWidth: 140
    },
    {
      label: "地区",
      prop: "address_path",
      minWidth: 180
    },
    {
      label: "客户标签",
      prop: "tag_ids",
      minWidth: 140,
      formatter: ({ tag_ids }) => {
        if (!tag_ids) return ''
        let tagIds = tag_ids.split(',').map(item => item.replaceAll('_', ''))
        return tagIds.map(item => labelList.value.find(tag => tag.id === item)?.name).join(',')
      }
    },
    {
      label: "数据来源",
      prop: "source",
      minWidth: 160,
      formatter: ({ source_by }) => {
        if (!source_by) return ''
        return sourceList.value.filter(item => item.value == source_by)[0].label
      }
    },
    {
      label: "群呼拨打次数",
      prop: "called_times",
      minWidth: 100
    },
    {
      label: "进入公海次数",
      prop: "insea_times",
      minWidth: 100
    },
    {
      label: "最新跟进人",
      prop: "target_staff_name",
      minWidth: 100
    },
    {
      label: "创建时间",
      prop: "created_at",
      minWidth: 120,
      formatter: ({ created_at }) =>  dayjs.unix(created_at).format("YYYY-MM-DD")
    },
    {
      label: "废弃时间",
      prop: "updated_at",
      minWidth: 120,
      formatter: ({ updated_at }) =>  dayjs.unix(updated_at).format("YYYY-MM-DD")
    },
    {
      label: "操作",
      fixed: "right",
      slot: "operation"
    }
  ];

  function lookCustomer(row) {
    detailRef.value.openDrawer(row.id);
  }

  function handleSizeChange(val: number) {
    form.size = val;
    pagination.pageSize = val
    onSearch(); // 刷新表格数据
  }

  function handleCurrentChange(val: number) {
    form.page = val;
    pagination.currentPage = val
    onSearch(); // 刷新表格数据
  }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;

    let queryFrom: any = { ...form };
    
    if (queryFrom.address && queryFrom.address.length) queryFrom.address = queryFrom.address.join('/')
    if (queryFrom.entry_at.length) {
      let startTime = dayjs(queryFrom.entry_at[0]).format("YYYY-MM-DD")
      let endTime = dayjs(queryFrom.entry_at[1]).format("YYYY-MM-DD")
      queryFrom.entry_at = `${startTime},${endTime}`
    }
    if (queryFrom.update_at.length) {
      let startTime = dayjs(queryFrom.update_at[0]).format("YYYY-MM-DD")
      let endTime = dayjs(queryFrom.update_at[1]).format("YYYY-MM-DD")
      queryFrom.update_at = `${startTime},${endTime}`
    }
    
    const result = await customer_list(toRaw(queryFrom));
    
    dataList.value = result.data.list;
    pagination.total = result.data.total;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    getLabelList()
    getUserList()
    
    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/customerManagement/data/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/customerManagement/data/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);
      console.log(homeDataObj)
      // cd_fq
      if (homeDataObj.cd_fq && homeDataObj.cd_fq.childs) {
        let permiss = homeDataObj.cd_fq.childs.join(',')
        permissions.is_cd_fq_table = permiss.includes('cd_fq_table') ? true : false

        if (permiss.includes('cd_fq_table')) onSearch();
      }
    }
  });

  // 获取客户标签
  function getLabelList() {
    tags_list({
      page: 1,
      pagesize: 999,
      status: 1
    }).then(res => {
      labelList.value = res.data
    })
  }

  // 获取用户列表
  function getUserList() {
    user_list({
      page: 1,
      pagesize: 999,
      status: "1"
    }).then(res => {
      userList.value = res.data
    })
  }

  return {
    permissions,
    
    shortcuts,
    labelList,
    sourceList,
    userList,
    form,
    loading,
    columns,
    dataList,
    pagination,

    onSearch,
    resetForm,
    lookCustomer,
    handleSizeChange,
    handleCurrentChange,

    handleOffline,
  };
}
